package com.zsrd.self.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zsrd.self.base.Result;
import com.zsrd.self.entity.SelfUser;
import com.zsrd.self.entity.vo.GenerateschemeVo;
import com.zsrd.self.handle.AppletHandle;
import com.zsrd.self.service.SelfUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <pre>
 * 小程序交互接口
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/3/25 13:28
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/applet")
public class AppletController {


    @Autowired
    private SelfUserService selfUserService;

    @Autowired
    private AppletHandle appletHandle;


    /**
     * 记录小程序用户
     */
    @PostMapping("/save")
    public Result save(@RequestBody SelfUser selfUser){
        QueryWrapper qw=new QueryWrapper();
        qw.eq("union_id",selfUser.getUnionId());
        SelfUser one = selfUserService.getOne(qw);
        if(one!=null){
            selfUser.setId(one.getId());
            selfUserService.updateById(selfUser);
            return Result.success("修改成功");
//            return Result.error("该用户已经提交过记录");
        }
        selfUser.setCreatTime(new Date());
        selfUserService.save(selfUser);
        return Result.success("新建成功");
    }

    //获取token
    @PostMapping("/getAccessToken")
    public Result getAccessToken(){
        return Result.success(appletHandle.getAccessToken());
    }

    //小程序获取跳转路径
    @PostMapping("/getScheme")
    public Result getScheme(@RequestBody GenerateschemeVo param){
        JSONObject jumpWx = new JSONObject();
        jumpWx.put("path",param.getPath());
        jumpWx.put("query",param.getQuery());
        jumpWx.put("env_version",param.getEnvVersion());
        return Result.success(appletHandle.getGenerateScheme(JSONObject.toJSONString(jumpWx)));
    }

    //小程序获取union等信息
    @PostMapping("/getCode2Session")
    public Result getCode2Session(@RequestBody GenerateschemeVo param){
        String jsCode=param.getCode();
        return Result.success(appletHandle.getCode2Session(jsCode));
    }

}
